import {NextRequest, NextResponse} from 'next/server'
import {getSession} from "@/lib/session";
import {cookies} from "next/headers";
import {addDays} from "date-fns";

export async function middleware(request: NextRequest) {
    const pathname = request.nextUrl.pathname;

    if(pathname ==='/logout'){
        //删除信息
        const ies = await cookies();
        ies.set("Authorization","",{
            expires:addDays(new Date(),-1)
        })

        return NextResponse.json({
            code:200,
            msg:"退出成功"
        });
    }

    if(pathname.startsWith("/home") || pathname.startsWith("/api")){
        const session = await getSession();
        if (!session) {
            return NextResponse.redirect(new URL("/login", request.url));
        }
    }
    return NextResponse.next();
}

export const config = {
    matcher: ['/home/:path*',"/logout"],
}
